import styled from '@emotion/styled';
import React, { useEffect } from 'react';
import { Checkbox, Input, Button } from 'antd';
import TableManagement from './TableManagement';
import { findAgents, getRoomToken, getSessionType } from '@/api';
import { useDispatch, useSelector } from 'react-redux';
import { useMenuContext } from '../Context/MenuContext';
import useSyncState from '../hooks/useSyncState';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
import ServiceMonitoringView from './ServiceMonitoring';
import Message from '@/utils/message';
import AgentService from '@/modules/Agent';
import { setSessionData } from '@/store/reducers/session';
import { useTranslation } from 'react-i18next';

const CheckboxGroup = Checkbox.Group;

const AgentManagement = styled.div`
	width: 100%;
	height: 100%;
	background: #ffffff;
	box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.12);
	margin: 16px 0;
`;

const GroupList = styled.div`
	margin-bottom: 20px;
`;

const ManagementCheckBox = styled(CheckboxGroup)`
	font-size: 13px;
	font-weight: 400;
	color: #202020;
	line-height: 18px;
`;

const GroupLabel = styled.span`
	font-size: 13px;
	font-weight: 400;
	color: #202020;
	line-height: 18px;
	margin-right: 10px;
`;

const ManagementContainer = styled.div`
	padding: 20px;
`;

const AgentStatus = styled.div`
	margin-bottom: 20px;
`;

const StatusLabel = styled.span`
	font-size: 13px;
	font-weight: 400;
	color: #202020;
	line-height: 18px;
	margin-right: 10px;
`;

const AgentName = styled.div`
	display: flex;
	align-items: center;
	padding-bottom: 20px;
`;

const NameLabel = styled.span`
	font-size: 13px;
	font-weight: 400;
	color: #202020;
	line-height: 18px;
	margin-right: 10px;
`;

const AgentNameInput = styled(Input)`
	width: 220px;
	height: 40px;
	background: #f6f6f6;
	border-radius: 4px;
	margin-right: 20px;
`;

const ResetButton = styled(Button)`
	width: 93px;
	height: 40px;
	border-radius: 4px;
	border: 1px solid #9d9ea4;
	margin-right: 12px;
	background: #ffffff;
	span {
		font-size: 13px;
		font-weight: 400;
		color: #7b7c85;
		line-height: 18px;
	}
	:focus {
		background: #ffffff;
	}
`;

const ScreenButton = styled(Button)`
	width: 93px;
	height: 40px;
	background: #252b48;
	border-radius: 4px;
	span {
		font-size: 13px;
		font-weight: 400;
		color: #ffffff;
		line-height: 18px;
	}
	:hover {
		background: #252b48;
	}
`;

const TableContainer = styled.div`
	border-top: 1px solid #e5e6eb;
`;

const TableManagementContainer = styled.div`
	.ant-table-wrapper {
		height: 100%;
		.ant-spin-nested-loading {
			height: 100%;
			.ant-spin-container {
				height: 100%;
				.ant-table {
					height: 100%;
					.ant-table-container {
						height: 100%;
					}
				}
			}
		}
	}
`;

interface IAgentManagementProps {
	joinSessionWithChief: () => void;
}

const index = (props: IAgentManagementProps) => {
	const { t } = useTranslation();
	const dispatch = useDispatch();
	const { joinSessionWithChief } = props;
	const { login, session } = useSelector((state: any) => state);

	const { chiefs, serviceMonitoringView, setServiceMonitoring, setRoomId } = useMenuContext();

	const [tableData, setTableData] = useSyncState([]);

	const [roomToken, setRoomToken] = useSyncState<string>('');

	const [searchData, setSearchData] = useSyncState<any>({}); //保存上一次调接口时传入的数据

	const [groupList, setGroupList] = useSyncState<CheckboxValueType[]>([]);

	const [statusList, setStatusList] = useSyncState<CheckboxValueType[]>([]);

	const [searchAgentName, setSearchAgentName] = useSyncState<string>('');

	const [IntervalFindAgents, setIntervalFindAgents] = useSyncState<any>(null);

	const [tableHeight, setTableHeight] = useSyncState<number>(0);

	const agentStatus = [
		// { value: 'online', label: t('checked-in') },
		{ value: 'notReady', label: t('not-ready-status') },
		{ value: 'ready', label: t('ready-status') },
		{ value: 'serving', label: t('calling') },
		{ value: 'ringing', label: t('ringing') },
		{ value: 'otherWork', label: t('taking-break') },
		{ value: 'afterWork', label: t('work-arrange') }
	];

	let timer: any = null;

	const getSkillGroups = () => {
		let arr: { value: number; label: string }[] = [];
		AgentService.checkedGroups.forEach((item: { id: number; name: string }) => {
			AgentService.isChiefsGroups.forEach((element: { groupId: number | any }) => {
				if (item.id === element.groupId) {
					arr.push({ value: item.id, label: item.name });
				}
			});
		});
		return arr;
	};

	//查询同一机构下其他坐席的通话状态
	const getAgentsConverSationStatus = async () => {
		let checkInfo: any = {
			page: '',
			pageSize: '',
			userName: '',
			agentStatus: '',
			groups: []
		};
		chiefs().forEach(item => {
			checkInfo.groups.push(item.data);
		});
		findAgentsStatus(checkInfo);
	};

	const findAgentsStatus = async (checkInfo: any) => {
		let arr: any = [];
		setSearchData(checkInfo);
		try {
			const { data } = await findAgents(checkInfo);
			console.log(data, 'findAgents');
			data.data.forEach((item: any) => {
				let obj: any = {
					agentName: '',
					userData: '',
					fullName: '',
					belongGroups: [],
					groups: [],
					currentStatus: '',
					toScenarioId: ''
				};
				obj.agentName = item.agentName;
				obj.userData = item.userData && item.userData[0].data ? item.userData[0].data : '';
				obj.belongGroups = [];
				obj.fullName = item.fullName || '';
				obj.groups = []; //item.groups;
				obj.currentStatus = item.currentStatus;
				item.belongGroups.forEach((groupData: any) => {
					obj.belongGroups.push(groupData.group.name);
					if (item.groups.indexOf(groupData.groupId) != -1) {
						obj.groups.push(groupData.group.name);
					}
				});
				let toScenarios: any = [];
				let toGroups: any = [];
				item.invites &&
					item.invites.forEach((invite: any) => {
						toScenarios.push(invite.toScenarioId);
						toGroups.push(invite.toGroup);
					});
				obj.toScenarioId = Array.from(new Set(toScenarios));
				obj.toGroup = Array.from(new Set(toGroups));
				obj.session = item.session;
				arr.push(obj);
			});
			console.log(arr, 'arr');
			dealWithManagentData(arr);
		} catch (error) {
			console.log(error, 'findAgents error');
		}
	};

	/**
	 * 处理通话管理的数据
	 */
	const dealWithManagentData = (data: any) => {
		let arr = data.map((item: any, index: number) => {
			return {
				key: index,
				serviceNo: item.agentName,
				name: item.agentName,
				fullName: item.fullName,
				belongSkillGroup: item.belongGroups.toString(),
				checkInSkillGroup: item.groups.toString(),
				currentStatus: item.currentStatus,
				session: item.session,
				toScenarioId: item.toScenarioId,
				toGroup: item.toGroup,
				userData: item.userData ? item.userData : ''
			};
		});
		for (let i = 0; i < arr.length; i++) {
			if (arr[i].currentStatus != 'serving') {
				arr[i]._disabled = true;
			}
		}
		console.log('agents session status origin data', arr);
		let managentData: any = [];
		arr.forEach((item: any) => {
			managentData.push(item);
		});
		setTableData(managentData);
		console.log('agents session status data', managentData);
	};

	useEffect(() => {
		getAgentsConverSationStatus();
		let data = setInterval(() => {
			findAgentsStatus(searchData());
		}, 5000);
		setIntervalFindAgents(data);
		return () => {
			clearInterval(IntervalFindAgents());
		};
	}, []);

	const groupChange = (groupList: CheckboxValueType[]) => {
		setGroupList(groupList);
	};

	const statusChange = (statsuList: CheckboxValueType[]) => {
		setStatusList(statsuList);
	};

	const changeAgentName = (e: any) => {
		setSearchAgentName(e.target.value);
	};

	//服务监控
	const serviceMonitoring = async (roomId: string, sessionId: string, agentName: string, userData: any) => {
		if (await getSessionIsIM(sessionId)) {
			Message.warning(t('agent-im-session'));
			return;
		}
		if (timer) {
			clearTimeout(timer);
			timer = null;
		}
		timer = window.setTimeout(async () => {
			let checkInfo: any = {
				page: '',
				pageSize: '',
				userName: agentName,
				agentStatus: '',
				groups: []
			};
			try {
				const { data } = await findAgents(checkInfo);
				console.log(data, 'findAgents');
				const servingItem = data.data.find((item: any) => item.session?.sessionId === sessionId && item.currentStatus === 'serving');
				if (servingItem) {
					const { invites } = servingItem;
					getAgentsRoomToken(roomId);
					AgentService.setSessionId(sessionId);
					setRoomId(roomId);
					// invites 获取转接后的sceenId
					if (invites && invites[0] && invites[0].toScenarioId) {
						const updateData = { userData, bizScenarioId: invites[0].toScenarioId };
						dispatch(setSessionData({ ...session, ...updateData }));
						AgentService.setBizScenarioId(invites[0].toScenarioId);
						AgentService.setUserCallData(userData);
					} else {
						dispatch(setSessionData({ ...session, userData }));
						AgentService.setBizScenarioId(session.bizScenarioId);
						AgentService.setUserCallData(userData);
					}
				} else {
					Message.warning(t('cannot-monitor-agent-not-in-call'));
				}
			} catch (error) {
				console.log(error, 'findAgents error');
			}
		}, 200);
	};

	const handleOk = () => {
		setServiceMonitoring(false);
		joinSessionWithChief && joinSessionWithChief();
	};

	const handleCancel = () => {
		AgentService.setSessionId('');
		setServiceMonitoring(false);
	};

	const getAgentsRoomToken = async (roomId: string) => {
		try {
			const data = await getRoomToken({
				room: roomId,
				user: AgentService.user?.userName ? AgentService.user?.userName : 'admin',
				role: 'presenter'
			});
			console.log(data, 'getAgentsRoomToken');
			setRoomToken(data.data);
			setServiceMonitoring(true);
		} catch (error) {
			console.log(error, 'get room token');
			Message.warning(t('cannot-monitor-agent-not-in-call'));
		}
	};

	const search = () => {
		let arr: any = [];
		chiefs().forEach(item => {
			arr.push(item.data);
		});
		let checkInfo: any = {
			page: '',
			pageSize: '',
			userName: searchAgentName(),
			agentStatus: statusList(),
			groups: groupList().length == 0 ? arr : groupList()
		};
		findAgentsStatus(checkInfo);
	};

	const getSessionIsIM = async (sessionId: string) => {
		try {
			const { data } = await getSessionType(sessionId);
			console.log(data, 'getSessionType success');
			if (data.data.media === 'im') {
				return true;
			} else {
				return false;
			}
		} catch (error) {
			console.log(error, 'getSessionType error');
			return false;
		}
	};

	const reset = () => {
		setGroupList([]);
		setStatusList([]);
		setSearchAgentName('');
	};

	return (
		<AgentManagement id="agent-management">
			<ManagementContainer>
				<GroupList>
					<GroupLabel>{t('skill-set')}：</GroupLabel>
					<ManagementCheckBox options={getSkillGroups()} value={groupList()} onChange={groupChange}></ManagementCheckBox>
				</GroupList>
				<AgentStatus>
					<StatusLabel>{t('agent-status')}：</StatusLabel>
					<ManagementCheckBox options={agentStatus} value={statusList()} onChange={statusChange}></ManagementCheckBox>
				</AgentStatus>
				<AgentName>
					<NameLabel>{t('agent-user-name')}：</NameLabel>
					<AgentNameInput placeholder={t('input-agent-no-or-user-name') as string} onChange={changeAgentName} value={searchAgentName()} />
					<ResetButton onClick={reset}>{t('reset')}</ResetButton>
					<ScreenButton type="default" onClick={search}>
						{t('filter')}
					</ScreenButton>
				</AgentName>
				<TableContainer>
					<TableManagementContainer id="table-container">
						<TableManagement TableData={tableData()} serviceMonitoring={serviceMonitoring} tableHeight={tableHeight()} />
					</TableManagementContainer>
				</TableContainer>
			</ManagementContainer>
			{serviceMonitoringView() ? <ServiceMonitoringView isModalOpen={serviceMonitoringView()} handleOk={handleOk} handleCancel={handleCancel} token={roomToken()} /> : undefined}
		</AgentManagement>
	);
};

export default index;
